<template>
  <div ref="partChartRef" class="chart-container"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'PieChart',
  props: {
    chartData: {
      type: Array,
      default: () => [
        { value: 335, name: '直接访问' },
        { value: 310, name: '邮件营销' },
        { value: 234, name: '联盟广告' },
        { value: 135, name: '视频广告' },
        { value: 1548, name: '搜索引擎' }
      ]
    },
    chartTitle: {
      type: String,
      default: '剩余还款组成'
    }
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    this.destroyChart();
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.updateChart();
      }
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.partChartRef);

      const option = {
        title: {
          text: this.chartTitle,
          left: 'center'
        },
        color: [
          '#FF6B6B', '#FFD166', '#06D6A0', '#118AB2', '#073B4C'
        ],
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.chartData.map(item => item.name)
        },
        series: [
          {
            name: '还款组成',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: this.chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      this.chart.setOption(option);
      window.addEventListener('resize', this.resizeChart);
    },
    updateChart() {
      if (this.chart) {
        this.chart.setOption({
          legend: {
            data: this.chartData.map(item => item.name)
          },
          series: [{
            data: this.chartData
          }]
        });
      }
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    destroyChart() {
      if (this.chart) {
        window.removeEventListener('resize', this.resizeChart);
        this.chart.dispose();
        this.chart = null;
      }
    }
  }
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
}
</style>
